package com.brooks.demo;

import sun.misc.Contended;

import java.util.concurrent.CountDownLatch;

/**
 * @Author mihutu
 * @Date 2020/10/10 14:45
 * @Version 1.0
 */
public class DemoCacheLine3 {
    /**
     * 循环次数
     */
    public static long COUNT = 1_0000_0000L;

    /**
     * 这里要注意的是long类型占8字节
     * 该注解能强制成员变量不在同一个内存行
     */
    @Contended
    private static class T {
        public volatile long x = 0L;
    }

    public static T[] arr = new T[2];

    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void main(String[] args) throws Exception{
        CountDownLatch latch = new CountDownLatch(2);
        Thread thread1 = new Thread(()->{
            for (int i=0;i<COUNT;i++){
                arr[0].x = i;
            }
            latch.countDown();
        });
        Thread thread2 = new Thread(()->{
            for (int i=0;i<COUNT;i++){
                arr[1].x = i;
            }
            latch.countDown();
        });
        final long start = System.nanoTime();
        thread1.start();
        thread2.start();
        latch.await();
        System.out.println((System.nanoTime()-start)/100_0000);
    }
}
